<?php

namespace app\admin\model;

use app\api\model\TieBaFile;
use app\common\enums\StatusEnum;
use app\common\service\Html;
use think\Db;

class TieBa extends \app\common\model\TieBa
{
    /**
     * 列表
     * @param $where
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getList($where)
    {
        $sql = static::field('id, oauth_id, type_id, is_top, praise, check_status, create_time');

        if ($where) {
            $sql->where($where);
        }

        // 非草稿
        $sql->where(['is_draft' => self::DRAFT_NO]);

        $data = $sql->paginate(null, false, ['query' => request()->param()]);
        $typeIds = [];
        $oauthIds = [];
        foreach ($data->items() as $key => $value) {
            $typeIds[$value['type_id']] = $value['type_id'];
            $oauthIds[$value['oauth_id']] = $value['oauth_id'];
        }

        $type = [];
        if ($typeIds) {
            $type = TieBaType::getColumn($typeIds);
        }

        $oauth = [];
        if ($oauthIds) {
            $oauth = Oauth::getColumnValue($oauthIds);
        }

        $model = $data->each(function ($item, $key) use ($type, $oauth) {
            $item['oauth_id'] = isset($oauth[$item['oauth_id']]) ? $oauth[$item['oauth_id']]['nickname'] : '未知';
            $item['isTopText'] = self::attributes('is_top', $item['is_top']);
            $item['type_id'] = isset($type[$item['type_id']]) ? $type[$item['type_id']] : '未知';
            $item['create_time'] = get_datetime($item['create_time']);
            $item['checkStatusText'] = self::attributes('check_status', $item['check_status']);
            $item['commentCount'] = TieBaComment::getCountByTie($item['id']);
            return $item;
        });

        // 获取总记录数
        $count = $model->total();
        return [
            'model' => $model,
            'count' => $count
        ];
    }

    /**
     * 获取一条数据详情
     * @param $id
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($id)
    {
        $model = static::field('t.id, t.oauth_id, o.nickname, o.head_img, tt.name, t.content, t.praise, t.is_top, t.check_status, t.create_time')
            ->alias('t')
            ->join('oauth o', 't.oauth_id = o.id')
            ->join('tie_ba_type tt', 't.type_id = tt.id')
            ->where([
                't.id' => $id,
                't.is_draft' => self::DRAFT_NO,
                'tt.status' => StatusEnum::ENABLED,
                'o.status' => StatusEnum::ENABLED
            ])->find();
            
        if ($model) {
            $model = $model->toArray();
            $model['content'] = Html::encode($model['content']);
            $model['create_time'] = get_datetime($model['create_time']);
            // 每条帖子下面的文件
            $files = TieBaFile::getListByTie([$model['id']]);
            $model['files'] = isset($files[$model['id']]) ? $files[$model['id']] : [];
        }
        
        return $model;
    }

    /**
     * 删除
     * @param $id
     */
    public static function deleteOne($id)
    {
        $model = static::get($id);
        if ($model) {
            $model->delete();
        }
    }

    /**
     * 修改状态
     * @param $id
     * @param $status
     */
    public static function checkOne($id, $status)
    {
        $model = static::get($id);
        if ($model) {
            $model->check_status = $status;
            $model->update_time = time();
            $model->save();
        }
    }

    /**
     * 修改置顶
     * @param $id
     */
    public static function topOne($id)
    {
        $model = static::get($id);
        if ($model) {
            $model->is_top = ($model->is_top == self::TOP) ? self::TOP_NO : self::TOP;
            $model->update_time = time();
            $model->save();
        }
    }

    /**
     * 添加修改
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function saveOne($data)
    {
        $saveData = [
            'name' => $data['name'],
            'status' => $data['status'],
            'sort_num' => $data['sort_num'],
            'update_time' => time()
        ];

        if (isset($data['id']) && $data['id'] > 0) {
            Db::name('tie_ba_type')
                ->where('id', $data['id'])
                ->data($saveData)
                ->update();
            $id = $data['id'];
        } else {
            $saveData['create_time'] = time();
            $id = Db::name('tie_ba_type')->insertGetId($saveData);
        }
        return $id;
    }

    /**
     * 计算每个帖子类型的参与人数
     * @param $typeIds
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function countByTie($typeIds)
    {
        return static::field('type_id, COUNT(*) AS count')
            ->where(['is_draft' => self::DRAFT_NO])
            ->where('type_id', 'in', $typeIds)
            ->group('type_id')
            ->select()
            ->column('count', 'type_id');
    }

    public static function deleteAll($ids)
    {
        // 删除帖子
        static::where('id', 'in', $ids)->delete();
        // 删除评论
        TieBaComment::deleteByTie($ids);
    }

    /**
     * 获取贴吧文件
     */
    public static function getFileByTieId($tieId)
    {
        $model = Db::name('tie_ba_file')->field('*')
            ->where([
                'tie_id' => $tieId
            ])->select();
        return $model;
    }
}